package cn.wizzer.app.web.modules.controllers.platform.zs;

import cn.wizzer.app.sys.modules.models.Sys_role;
import cn.wizzer.app.sys.modules.models.Sys_user;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.framework.base.Result;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.framework.page.datatable.DataTableColumn;
import cn.wizzer.framework.page.datatable.DataTableOrder;
import cn.wizzer.framework.util.StringUtil;
import cn.wizzer.app.zs.modules.models.Complaint;
import cn.wizzer.app.zs.modules.services.ComplaintService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@IocBean
@At("/platform/zs/complaint")
public class ComplaintController {
    private static final Log log = Logs.get();
    @Inject
    private ComplaintService zsComplaintService;
    @Inject
    private SysUserService userService;

    @At("")
    @Ok("beetl:/platform/zs/complaint/index.html")
    @RequiresPermissions("platform.zs.complaint")
    public void index() {
    }

    @At("/handle")
    @Ok("beetl:/platform/zs/complaint/index_handle.html")
    @RequiresPermissions("platform.zs.complaint")
    public void handleList() {

    }


    @At("/dataHandle")
    @Ok("json:full")
    @RequiresPermissions("platform.zs.complaint")
    public Object dataHandle(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
        Sys_user user = userService.fetch(StringUtil.getUid());
        userService.fetchLinks(user,"roles");
        List<Sys_role> roles = user.getRoles();
        Cnd cnd = Cnd.NEW();
        for (Sys_role role : roles){
            if (role.getCode().equals("technicalServiceAdmin") || role.getCode().equals("sysadmin") ){
                return zsComplaintService.data(length, start, draw, order, columns, cnd, null);
            }
        }
        cnd.and("status", "=", Globals.beforeHandle).or("handler", "=", StringUtil.getUid());
        return zsComplaintService.data(length, start, draw, order, columns, cnd, null);
    }



    @At("/data")
    @Ok("json:full")
    @RequiresPermissions("platform.zs.complaint")
    public Object data(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
        Cnd cnd = Cnd.NEW();
        return zsComplaintService.data(length, start, draw, order, columns, cnd, null);
    }

    @At("/add")
    @Ok("beetl:/platform/zs/complaint/add.html")
    @RequiresPermissions("platform.zs.complaint")
    public void add(HttpServletRequest req) {
        req.setAttribute("uid",StringUtil.getUid());
    }

    @At("/accepting")
    @Ok("json")
    public Object accepting(@Param("complaintId") String complaintId, HttpServletRequest req) {
        try {
            Complaint complaint = zsComplaintService.fetch(complaintId);
            complaint.setStatus(Globals.handling);
            complaint.setHandler(StringUtil.getUid());
            zsComplaintService.updateIgnoreNull(complaint);
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/addDo")
    @Ok("json")
    @RequiresPermissions("platform.zs.complaint")
    @SLog(tag = "投诉", msg = "${args[0].id}")
    public Object addDo(@Param("..") Complaint zsComplaint, HttpServletRequest req) {
        try {
            zsComplaint.setStatus(0);
            zsComplaintService.insert(zsComplaint);
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/edit/?")
    @Ok("beetl:/platform/zs/complaint/edit.html")
    @RequiresPermissions("platform.zs.complaint")
    public void edit(String id, HttpServletRequest req) {
        req.setAttribute("obj", zsComplaintService.fetch(id));
    }

    @At("/editDo")
    @Ok("json")
    @RequiresPermissions("platform.zs.complaint.edit")
    @SLog(tag = "投诉", msg = "${args[0].id}")
    public Object editDo(@Param("..")Complaint zsComplaint, HttpServletRequest req) {
		try {
            zsComplaint.setOpBy(StringUtil.getUid());
			zsComplaint.setOpAt((int) (System.currentTimeMillis() / 1000));
			zsComplaintService.updateIgnoreNull(zsComplaint);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }

    @At({"/delete/?", "/delete"})
    @Ok("json")
    @RequiresPermissions("platform.zs.complaint.delete")
    @SLog(tag = "投诉", msg = "${req.getAttribute('id')}")
    public Object delete(String id, @Param("ids")  String[] ids, HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				zsComplaintService.delete(ids);
    			req.setAttribute("id", org.apache.shiro.util.StringUtils.toString(ids));
			}else{
				zsComplaintService.delete(id);
    			req.setAttribute("id", id);
			}
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/detail/?")
    @Ok("beetl:/platform/zs/complaint/detail.html")
    @RequiresPermissions("platform.zs.complaint")
    public void detail(String id, HttpServletRequest req) {
        if (!Strings.isBlank(id)) {
            Complaint complaint = zsComplaintService.fetch(id);
            Sys_user user = userService.fetch(complaint.getFounder());
            req.setAttribute("obj", complaint);
            req.setAttribute("founder", user.getUsername());
            if (complaint.getStatus() == 3){
                req.setAttribute("feedbackPerson",userService.fetch(complaint.getFeedbackPerson()).getUsername());
            }else {
                req.setAttribute("feedbackPerson","");
            }
        } else {
            req.setAttribute("obj", null);
            req.setAttribute("founder", "");
            req.setAttribute("feedbackPerson","");
        }
    }


    @At("/handlePage/?")
    @Ok("beetl:/platform/zs/complaint/handlePage.html")
    @RequiresPermissions("platform.zs.complaint")
    public void handlePage(String id,HttpServletRequest req) {
            req.setAttribute("obj", zsComplaintService.fetch(id));
    }

    @At("/noHandlePage/?")
    @Ok("beetl:/platform/zs/complaint/noHandlePage.html")
    @RequiresPermissions("platform.zs.complaint")
    public void noHandlePage(String id,HttpServletRequest req) {
        req.setAttribute("obj", zsComplaintService.fetch(id));
    }

    @At("/handleDo")
    @Ok("json")
    public Object handleDo(@Param("..")Complaint zsComplaint, HttpServletRequest req) {
        Complaint complaint = zsComplaintService.fetch(zsComplaint.getId());
        try {
            complaint.setOpBy(StringUtil.getUid());
            complaint.setOpAt((int) (System.currentTimeMillis() / 1000));
            complaint.setHandling(zsComplaint.getHandling());
            complaint.setStatus(Globals.afterHandle);
            zsComplaintService.updateIgnoreNull(complaint);
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/noHandleDo")
    @Ok("json")
    public Object noHandleDo(@Param("..")Complaint zsComplaint, HttpServletRequest req) {
        Complaint oldcomplaint = zsComplaintService.fetch(zsComplaint.getId());
        try {
            oldcomplaint.setOpBy(StringUtil.getUid());
            oldcomplaint.setOpAt((int) (System.currentTimeMillis() / 1000));
            oldcomplaint.setReason(zsComplaint.getReason());
            oldcomplaint.setStatus(Globals.no_handling);
            zsComplaintService.updateIgnoreNull(oldcomplaint);
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/feedbackPage/?")
    @Ok("beetl:/platform/zs/complaint/feedbackPage.html")
    @RequiresPermissions("platform.zs.complaint")
    public void feedbackPage(String id,HttpServletRequest req) {
        req.setAttribute("obj", zsComplaintService.fetch(id));
    }

    @At("/feedbackDo")
    @Ok("json")
    public Object feedbackDo(@Param("..")Complaint zsComplaint, HttpServletRequest req) {
        Complaint tempComplaint = zsComplaintService.fetch(zsComplaint.getId());
        try {
            tempComplaint.setOpBy(StringUtil.getUid());
            tempComplaint.setOpAt((int) (System.currentTimeMillis() / 1000));
            tempComplaint.setStatus(Globals.feedback);
            tempComplaint.setFeedbackPerson(StringUtil.getUid());
            tempComplaint.setFeedback(zsComplaint.getFeedback());
            zsComplaintService.updateIgnoreNull(tempComplaint);
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }


}
